using System.Collections.Generic;
using GoGameClient.script.global;
using Godot;
using GoGameClient.script.resources;

namespace GoGameClient.script.map;

public partial class TrendsMap : TileMap
{
    private int WindowWidth { get; set; }
    private int WindowHeight { get; set; }
    private ResourcesControl _resourcesControl;
    private MapInfo _mapInfo;

    private int ColCount { get; set; }
    private int RowCount { get; set; }

    public override void _Ready()
    {
        _resourcesControl = ResourcesControl.Instance();
        AddLayer(1);
        SetLayerZIndex(1, 2);
        WindowWidth = GetWindow().Size.X;
        WindowHeight = GetWindow().Size.Y;
        TileSet = new TileSet();
    }

    public void UpdateMapInfo()
    {
        _mapInfo = _resourcesControl.GetCurrentMapInfo();
        ColCount = ComputeColCount();
        RowCount = ComputeColCount();
        TileSet.TileSize = new Vector2I(_mapInfo.Col, _mapInfo.Row);
    }


    public override void _Process(double delta)
    {
        if (_mapInfo == null) return;
        SetTileCell(_resourcesControl.TryGetMapTile(), 0);
        SetTileCell(_resourcesControl.TryGetMaskTile(), 1);
    }

    private void SetTileCell(IList<TileInfo> list, int layer)
    {
        if (list == null)
        {
            return;
        }

        foreach (var tileInfo in list)
        {
            SetCell(layer, tileInfo.Offset, TileSet.AddSource(tileInfo.TileSetAtlasSource), new Vector2I(0, 0));
        }
    }

    private int ComputeColCount()
    {
        return (WindowWidth / _mapInfo.Col) + 1;
    }

    private int ComputeRowCount()
    {
        return (WindowHeight / _mapInfo.Row) + 1;
    }

    public void DrawMap(Vector2I position)
    {
        InitMap(position);
    }

    private void InitMap(Vector2I position)
    {
        for (var y = -RowCount; y <= RowCount; y++)
        {
            for (var x = -ColCount; x <= ColCount; x++)
            {
                var offset = new Vector2I(position.X + x, position.Y + y);
                if (offset.X < 0 || offset.Y < 0)
                {
                    continue;
                }

                if (_mapInfo.MapColNum <= offset.X || _mapInfo.MapRowNum <= offset.Y)
                {
                    continue;
                }

                if (GetCellSourceId(0, offset) != -1)
                {
                    continue;
                }

                _resourcesControl.ApplyTile(offset);
            }
        }
    }
}